// 时间选择相关的处理函数
import dayjs from 'dayjs';
/**
 * 按照时间间隔生成时间数组，类似：['00: 15', '00:30' ....]
 * @param {Number} interval 时间间隔
 */
const createTimePartArray = (interval) => {
    let result = [];
    for (let i = 0; i < 24; i++) {
        for (let j = 0; j < 60;) {
            result.push(`${intToTimeString(i)}:${intToTimeString(j)}`);
            j += interval;
        }
    }
    return result;
};

/**
 * 把数字转换成时间中需要的格式，如：0 => 00, 1 => 01
 * @param {Number} num 需要转换的数字
 */
const intToTimeString = (num) => {
    return num < 10 ? `0${num}` : `${num}`;
};
/**
 * 返回可用的开始和结束时间，用来处理奇怪的时间
 * @param {String} start 开始时间
 * @param {String} end 结束时间
 * @param {Number} interval 时间间隔
 */
const getAvilableStartAndEndTime = (start, end, interval=15, isToday=true) => {
    let result_start_h = '';
    let result_start_m = '';
    let result_end_h = '';
    let result_end_m = '';
    const startArray = start.split(':');
    const start_h = parseInt(startArray[0]);
    const start_m = parseInt(startArray[1]);
    if (isToday) {
        const now_h = dayjs().hour();
        const now_m = dayjs().minute();
        if (start_h > now_h) {
            result_start_h = start_h;
            result_start_m = start_m;
        } else if (start_h === now_h) {
            result_start_h = start_h;
            result_start_m = start_m > now_m ? start_m : now_m;
        } else {
            result_start_h = now_h;
            result_start_m = now_m;
        }
    } else {
        result_start_h = start_h;
        result_start_m = start_m;
    }
    const endArray = end.split(':');
    result_end_h = parseInt(endArray[0]);
    result_end_m = parseInt(endArray[1]);

    return {
        start: `${intToTimeString(result_start_h)}:${intToTimeString(result_start_m + (interval - result_start_m % interval))}`,
        end: `${intToTimeString(result_end_h)}:${intToTimeString(result_end_m + (interval - result_end_m % interval))}`,
    };
};

const timePartMerge = (arr=[], date) => {
    let result = [];
    for (let i = 0; i < arr.length; i++) {
        if (i === arr.length - 1) {
            break;
        }
        result.push(`${arr[i]}~${arr[i+1]}`);
    }
    return result;
};

/**
 * 按照特定的时间间隔拆分时间为时间段
 * @param {String} start 开始时间字符串
 * @param {String} end 结束时间字符串
 * @param {Number} interval 相邻两个时间段之间的时间间隔，默认15分钟
 */
export const dealTimeToTimePart = (startTime, endTime, interval=15) => {
    // start = '6:30';
    // end = '20:30';
    // 生成包含所有的时间数组
    const { start, end } = getAvilableStartAndEndTime(startTime, endTime, interval);
    const timeArray = createTimePartArray(interval);
    const valueArray = timeArray.slice(timeArray.indexOf(start), timeArray.indexOf(end) + 1);
    return timePartMerge(valueArray);
};


/**
 * 返回可用的日期选择数据
 * @param {Number} length
 */
export const getAviableDay = (length=1) => {
    let result = [];
    const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    for (let i = 0; i < length; i++) {
        let day = dayjs().add(i, 'days');
        let text = day.format('MM-DD');
        let week = dayjs(day).day();
        if (i === 0) {
            text = '今天';
        }
        if (i === 1) {
            text = '明天';
        }
        result.push({
            text,
            week: weeks[week],
            value: day.format('YYYY-MM-DD'),
        });

    }
    return result;
};

/**
 * 时间枚举转换为显示的文字
 * @param {Array} range 时间枚举
 */
export const timeRangeToString = (range, day, isTakeout=false, isHaveNow=true) => {
    const isToday = dayjs(day).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD');
    const isTomorrow = dayjs(day).format('YYYY-MM-DD') === dayjs().add('day', 1).format('YYYY-MM-DD');
    const result = range.map((item, index) => {
        const startTime = dayjs(`${day} ${item.begin}:00`).valueOf();
        const endTime = dayjs(`${day} ${item.end}:00`).valueOf();
        const showTextPrefix = isToday ? '今天' : isTomorrow ? '明天' : dayjs(day).format('YYYY-MM-DD');
        return {
            key: (isTakeout && isToday && isHaveNow) ? index + 1 : index,
            day,
            text: `${item.begin}~${item.end}`,
            showText: `${showTextPrefix} ${item.begin}~${item.end}`,
            value: [startTime / 1000, endTime / 1000],
            marketValue: {
                bookBegin: startTime,
                bookEnd: endTime - 1,
            },
        };
    });
    if (isTakeout && isToday && isHaveNow) {
        result.unshift({
            key: 0,
            day,
            text: '尽快送达',
            showText: '尽快送达',
            value: null,
            marketValue: null,
        });
    }
    return result;
};

/**
 * 根据时间戳返回显示的预约时间
 * @param {Array} range 当前预约时间戳数据
 */
export const rangeToTipString = (range) => {
    const format_one = 'MM-DD';
    const format_two = 'HH:mm';
    const tody = dayjs().format(format_one);
    const tomorrow = dayjs().add(1, 'days').format(format_one);
    const start = dayjs(range[0] * 1000);
    const end = dayjs(range[1] * 1000);
    let beforeText = start.format(format_one);
    if (beforeText === tody) {
        beforeText = '今天';
    }
    if (beforeText === tomorrow) {
        beforeText = '明天';
    }
    return `${beforeText} ${start.format(format_two)}~${end.format(format_two)}`;
};

export const getAvailableTime = (time) => {
    const now = dayjs().valueOf();
    const _time = dayjs(time * 1000);
    if (_time < now) {
        return false;
    }
    return time;
};

export const isToday = (time) => {
    const time_value = dayjs(time).format('YYYY-MM-DD');
    const now_value = dayjs().format('YYYY-MM-DD');
    if (now_value === time_value) {
        return true;
    }
    return false;
};

export const parseTime = (time) => {
    const SECOND = 1000;
    const MINUTE = 60 * SECOND;
    const HOUR = 60 * MINUTE;
    const DAY = 24 * HOUR;
    const days = Math.floor(time / DAY);
    const hours = Math.floor((time % DAY) / HOUR);
    const minutes = Math.floor((time % HOUR) / MINUTE);
    const seconds = Math.floor((time % MINUTE) / SECOND);
    const milliseconds = Math.floor(time % SECOND);

    return {
        days,
        hours,
        minutes,
        seconds,
        milliseconds,
    };
};
